package com.lzy.blog.realm;

import com.lzy.blog.enums.ResultEnum;
import com.lzy.blog.exception.BlogException;
import com.lzy.blog.pojo.Admin;
import com.lzy.blog.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: lzy_blog
 * @description: 管理员的授权和登录
 * @author: lzy
 * @create: 2020-06-06 23:05
 **/
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 登录认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken =(UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        //接收用户参数
        Admin admin = adminService.getByUserName(username);
        //判断
        if(null == admin){
            throw new BlogException(ResultEnum.ERROR.getCode(),"用户不存在");
        }
        return new SimpleAuthenticationInfo(admin,admin.getPassword(),this.getName());
    }
}
